/*
 * @Description: 档案检测方案列表
 * @Author: Rfan
 * @Date: 2022-10-09 15:57:24
 * @LastEditTime: 2022-10-21 18:12:34
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { formatDate, isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useArchivesDetectionContext } from '../contexts/ArchivesDetectionContext';
import type { IPageQuery } from '@/interfaces/global';
import type { IFetchDetectionListByPageParams } from '@/api/standardizedDetection/detectionPlan';
import styles from '../styles/pageList.module.scss';
import AddPlan from './dialogs/AddPlan';
import { EnumDialogType } from './dialogs/AddPlan/contexts/AddPlanDialogContext';
import { selectItemByKey } from '@/utils/list';

const cx = classNames.bind(styles);
const { Column } = Table;

const PageList = () => {
  const {
    selectAT,
    list,
    selectItems,
    setSelectKey,
    checkedObjTypeList,
    getPlanList,
    delDetectionPlanFunc,
    getCheckObjName
  } = useArchivesDetectionContext();
  const formatMessage = useFormatMessage();

  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<IPageQuery<IFetchDetectionListByPageParams>>({
    pageNo: 1,
    pageSize: 10,
    param: { archiveTypeId: selectAT.id, atCode: selectAT.atCode, atType: selectAT.atType }
  });
  // 加入鉴定批次弹窗可视状态
  const [addPlanVisible, setAddPlanVisible] = useState(false);
  // 选中的条目

  const [editItem, setEditItem] = useState(null);

  useEffect(() => {
    if (selectAT?.id) {
      setListQuery({
        pageNo: 1,
        pageSize: 10,
        param: {
          archiveTypeId: selectAT.id,
          atCode: selectAT.atCode,
          atType: selectAT.atType
        }
      });
    }
  }, [selectAT]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param) && listQuery.param?.archiveTypeId) {
      setLoading(true);
      getPlanList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const showAddPlan = (item: any) => {
    setEditItem(item);
    setAddPlanVisible(true);
  };

  return (
    <div>
      <Table
        dataSource={list}
        loading={loading}
        rowKey="id"
        scroll={{ x: 'max-content' }}
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column title="方案名称" dataIndex="schemeName" key="schemeName" align="center" />
        <Column
          title="检测对象"
          dataIndex="detectionObjType"
          key="detectionObjType"
          align="center"
          render={(text) => getCheckObjName(text)}
        />
        <Column title="修改人" dataIndex="operatorName" key="operatorName" align="center" />
        <Column
          title="修改时间"
          dataIndex="operatorTime"
          key="operatorTime"
          align="center"
          render={(text) => formatDate(text)}
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          className={cx('action-col')}
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  showAddPlan(record);
                }}
              >
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  delDetectionPlanFunc(record.id);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
      </Table>
      {useMemo(
        () =>
          editItem && (
            <AddPlan
              visible={addPlanVisible}
              type={EnumDialogType.edit as 'edit'}
              checkedObjType={selectItemByKey(editItem.detectionObjType, checkedObjTypeList)}
              data={editItem}
              onClose={() => {
                setAddPlanVisible(false);
              }}
            />
          ),
        [addPlanVisible]
      )}
    </div>
  );
};

export default PageList;
